<template>
  <view :style="{ paddingTop: outPaddingTop, background: backgroundColor }">
    <scroll-view
      scroll-y="true"
      :style="{ height: showLoading || showAllList ? loadingHeight : mainHeight }"
      :refresher-enabled="true"
      :refresher-triggered="triggered"
      :refresher-threshold="80"
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      @scroll="scroll"
    >
      <slot></slot>
    </scroll-view>
    <view class="loading" v-if="showLoading">
      正在加载，请稍候
      <uni-icons type="spinner-cycle" size="16" style="margin-left: 4px;"></uni-icons>
    </view>
    <view class="all-data" v-if="showAllList">已加载全部数据~</view>
  </view>
</template>

<script>
export default {
  name: 'YouScroll',

  data() {
    return {
      showLoading: false,
      showAllList: false,
      triggered: false,
      lastScrollTop: 0, // 上一次滚动的 scrollTop 值
    }
  },
  props: {
    loadingHeight: { // 有加载文字的高度
      type: String
    },
    mainHeight: { // 没有加载文字的高度
      type: String
    },
    isAllData: { // 数据是否已经展示全部
      type: Boolean
    },
    isRequestSuccess: { // 接口是否已经请求完成
      type: Boolean
    },
    outPaddingTop: { // 顶部的padding
      type: [String, Number],
      default: 0
    },
    backgroundColor: { // 背景色
      type: String
    }
  },
  watch: {
    isAllData: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.showAllList = true
          this.showLoading = false
          uni.showToast({ title: '已经是最后一页了~', icon: 'none' })
        } else {
          this.showLoading = true
        }
      },
      deep: true
    },
    isRequestSuccess: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.showLoading = false
          this.triggered = false
          this._freshing = false
        }
      },
      deep: true
    }
  },
  onLoad() {

    this._freshing = false
  },
  methods: {
    // 列表滚动
    scroll($event) {
      const scrollTop = $event.detail.scrollTop
      if (scrollTop < this.lastScrollTop) {
        this.showAllList = false
      }
      this.lastScrollTop = scrollTop
      this.$emit('scroll', scrollTop)
    },
    // 下拉刷新
    onRefresh() {
      if (this._freshing) return
      this._freshing = true
      this.triggered = true
      this.showAllList = false
      this.$emit('onRefresh')
    },
    // 上拉加载
    loadMore() {
      if (this.isAllData) {
        this.showAllList = true
        this.showLoading = false
      } else {
        this.showLoading = true
      }
      this.$emit('loadMore')
    }
  }
}
</script>

<style lang="less" scoped>
.loading,
  .all-data {
    display: flex;
    justify-content: center;
    align-items: center;
    color: #999;
  }
</style>